<?php
declare(strict_types=1);


namespace App\Hoenix\Mapper;

use App\Hoenix\Model\HoenixKeyword;
use App\Hoenix\Model\HoenixKeywordIndex;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 索引关联词Mapper类
 */
class HoenixKeywordIndexMapper extends AbstractMapper
{
    /**
     * @var HoenixKeywordIndex
     */
    public $model;

    public function assignModel()
    {
        $this->model = HoenixKeywordIndex::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        $query->where(['idx' => $params['idx']]);
        return $query->with(['keyword']);
    }

    public function save(array $data): mixed
    {
        $kw = HoenixKeyword::query()->firstOrCreate(['kw' => $data['keyword']]);
        $md = $this->model::query()->firstOrCreate(['kid' => $kw->id, 'idx' => $data['idx']]);
        return $md->id;
    }
}